<template>
  <div class="container">
    <el-dialog
      title="添加订单"
      :visible.sync="addDialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="99%"
    >
      <el-select
        style="margin-bottom: 5px"
        v-model="organization"
        :multiple="false"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请选择客户"
        :remote-method="organizationMethod"
        :loading="insides.loading"
      >
        <el-option
          v-for="item in insides.option"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="请搜索选择商品"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        max-height="500"
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="商品编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="spec"
          label="规格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="netnum"
          label="库存"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="cost_price"
          label="成本价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="order_price"
          label="订单价格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="stockRemoval"
          label="订单总额"
          align="center"
        ></el-table-column>
        <el-table-column label="选择批次商品" align="center" width="150px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.batch_id"
              placeholder="请选择批次商品"
              @change="getOptionId(scope.row.batch_id, scope)"
            >
              <el-option
                v-for="item in scope.row.unAvgBatchData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="orderNum(scope)"
              :controls="false"
              v-model="scope.row.order_num"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="加价" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="markup(scope)"
              :controls="false"
              v-model="scope.row.markup"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="预提费" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="markup(scope)"
              :controls="false"
              v-model="scope.row.withholding_fee"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="件数" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="qrtnum(scope)"
              :controls="false"
              v-model="scope.row.qrtnum"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getOrgData,
  addSaleOrder,
  selectGoodsBatch,
} from "@/api/middleorder/middleorderlist";
import { commodityList } from "@/api/commodity/commodityList"; //商品
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
export default {
  props: {
    addDialog: Object,
  },
  data() {
    return {
      tableData: [],
      batch_id: "",
      commodity: "",
      is_assign: false,
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      insides: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      orgvalue: {
        org_id: "",
        org_code: "",
        org_name: "",
      },
      ispici: false,
      isnum: false,
      OrgDatalist: [],
      search: {
        goods_code: "",
        org_code: "",
      },
      organization: "",
      priceNum: 0,
    };
  },
  methods: {
    //取消
    cancel() {
      this.addDialog.centerDialogVisible = false;
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.insides = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.is_assign = false;
      this.commodity = "";
      this.organization = "";
      this.tableData = [];
      (this.ispici = false),
        (this.isnum = false),
        (this.search = {
          goods_code: "",
          org_code: "",
        });
      (this.OrgDatalist = []),
        (this.orgvalue = {
          org_id: "",
          org_code: "",
          org_name: "",
        });
    },
    getData() {
      let data = {
        page: 1,
        limit: 500,
        search: this.search.goods_code,
      };
      //获取商品
      commodityList(data).then((res) => {
        this.goodsList = res.data.data;
        if (res.data.data) {
          this.inside.option = res.data.data.map((item) => {
            return { value: `${item.code}`, label: `${item.name}` };
          });
        }
      });
    },
    openData() {
      this.getDatas();
      this.getData();
    },
    getDatas() {
      let data = {
        page: 1,
        limit: 500,
        key: this.search.org_code,
      };
      //获取机构
      getOrgData(data).then((res) => {
        this.OrgDatalist = res.data;
        if (res.data) {
          this.insides.option = res.data.map((item) => {
            return { value: `${item.erp_org_code}`, label: `${item.name}` };
          });
        }
      });
    },
    //修改加价
    markup(scope) {
      //订单总额
      scope.row.order_price = (
        parseFloat(scope.row.cost_price) +
        parseFloat(scope.row.markup) +
        parseFloat(scope.row.withholding_fee)
      ).toFixed(4);
      scope.row.stockRemoval = (
        scope.row.order_price * scope.row.order_num
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //修改数量
    orderNum(scope) {
      scope.row.stockRemoval = (
        scope.row.order_price * scope.row.order_num
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //件数
    qrtnum(scope) {
      console.log(scope.row.qrtnum, 44444455);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //删除
    remove(scope) {
      let id = scope.row.erp_goods_code;
      this.tableData.forEach((res, index) => {
        if (res.erp_goods_code == id) {
          this.tableData.splice(index, 1);
        }
      });
      this.priceNum = 0;
    },
    // 添加商品
    addGoods() {
      console.log(this.commodity, 333444);
      if (this.commodity) {
        let every = this.tableData.filter((res) => {
          return (
            res.Code == this.commodity || res.erp_goods_code == this.commodity
          );
        });
        if (every.length == 0) {
          let arr = this.goodsList.filter((res) => {
            return res.code == this.commodity;
          });
          console.log(arr, 88888);
          arr[0].unAvgBatchData = [];
          this.openSupplie(arr[0]);
        } else {
          this.$message({
            type: "info",
            message: "该商品已添加",
          });
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      }
    },
    //获取供应商
    openSupplie(scope) {
      let data = {
        goods_code: scope.code,
      };
      selectGoodsBatch(data).then((res) => {
        res.data.batch_list.forEach((item) => {
          scope.unAvgBatchData.push({
            value: item.id,
            label: `(${item.id})` + item.goods_name,
            price: item.inp_price,
            netnum: item.stock_net_num,
            spec: item.spec,
            erp_goods_id: item.erp_goods_id,
            goods_id: item.goods_id,
          });
        });
      });

      this.tableData.push({
        erp_goods_code: scope.code,
        goods_name: scope.name,
        erp_goods_id: 0,
        goods_id: 0,
        unit: scope.unit,
        spec: scope.spec || "",
        order_price: 0,
        order_num: 0,
        cost_price: 0,
        netnum: 0,
        markup: 0,
        stockRemoval: 0,
        qrtnum: 0,
        batch_id: "",
        withholding_fee: 0,
        unAvgBatchData: scope.unAvgBatchData,
      });
      console.log(this.tableData, 22222);
    },
    //选择批次取ID
    getOptionId(e, scope) {
      let data = scope.row.unAvgBatchData.filter((res) => {
        return res.value == e;
      });
      this.tableData[scope.$index].batch_id = data[0].value;
      this.tableData[scope.$index].cost_price = data[0].price;
      this.tableData[scope.$index].netnum = data[0].netnum;
      this.tableData[scope.$index].spec = data[0].spec;
      this.tableData[scope.$index].goods_id = data[0].goods_id;
      this.tableData[scope.$index].erp_goods_id = data[0].erp_goods_id;

      //订单总额
      scope.row.order_price = (
        parseFloat(scope.row.cost_price) +
        parseFloat(scope.row.markup) +
        parseFloat(scope.row.withholding_fee)
      ).toFixed(4);
      scope.row.stockRemoval = (
        scope.row.order_price * scope.row.order_num
      ).toFixed(4);
    },
    // 获取商品方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //获取商品数据
    getSupplierList(query) {
      this.search.goods_code = query;
      this.getData();
    },
    // 嵌套搜索客户数据
    organizationMethod(query) {
      if (query !== "") {
        this.organizationList(query);
      } else {
        this.insides.option = [];
      }
    },
    //获取客户数据
    organizationList(query) {
      this.search.org_code = query;
      this.getDatas();
    },
    //确定
    confirm() {
      this.OrgDatalist.forEach((item) => {
        if (this.organization == item.erp_org_code) {
          this.orgvalue.org_id = item.id;
          this.orgvalue.org_code = item.erp_org_code;
          this.orgvalue.org_name = item.name;
        }
      });

      this.tableData.forEach((res) => {
        if (res.batch_id) {
          this.ispici = true;
        } else {
          this.ispici = false;
          return;
        }
      });

      this.tableData.forEach((res) => {
        if (res.order_num) {
          this.isnum = true;
        } else {
          this.isnum = false;
          return;
        }
      });

      if (!this.orgvalue.org_id) {
        this.$message({
          type: "info",
          message: "请选择商店",
        });
        return;
      }
      if (!this.ispici) {
        this.$message({
          type: "info",
          message: "请选择批次",
        });
        return;
      }

      if (!this.isnum) {
        this.$message({
          type: "info",
          message: "请填写数量",
        });
        return;
      }
      let arr = [];
      this.tableData.forEach((res) => {
        arr.push({
          goods_id: res.goods_id,
          erp_goods_id: res.erp_goods_id,
          erp_goods_code: res.erp_goods_code,
          goods_name: res.goods_name,
          order_num: res.order_num,
          qty: res.qrtnum,
          markup: res.markup,
          withholding_fee: res.withholding_fee,
          batch_id: res.batch_id,
        });
      });

      let data = {
        org_id: this.orgvalue.org_id,
        org_code: this.orgvalue.org_code,
        org_name: this.orgvalue.org_name,
        goods: JSON.stringify(arr),
      };

      addSaleOrder(data).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: res.msg || res.message,
          });
          this.$emit("upData");
          this.cancel();
        }
      });
    },
  },
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}
.top {
  margin-bottom: 5px;
}
</style>